import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Button,
  Modal,
  Form,
  message,
  Input,
  Icon,
  Drawer,
  Menu, Dropdown, Select, TreeSelect, Popover,Tooltip
} from 'antd';
import moment from 'moment'
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';

import debounce from 'lodash/debounce';
import { renderValveOpen, afterCloseModal, renderTreeNodes,popoverPrice,download,formateObjToParamStr ,renderSignalIntensity} from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import Detail from './Detail';
import PayForm from './OwnerPay';
import ChangeMeter from './ChangeMeter';
import ReactDataGrid from 'react-data-grid';
import AddOrEditOwner from './AddOrEditOwner';
import AddOrEditAccount from './AddOrEditAccount';
import ExportMeterData from './ExportMeterData';
import ChangeInitValue from './ChangeInitValue';
import Area from './Area';
import request from '@/utils/request';
import stop from './../../images/stop.png'
import config from '../../config/config'
const { confirm } = Modal;
const FormItem = Form.Item;
const InputGroup = Input.Group;
const Option = Select.Option
@connect(({ owner, loading, global }) => ({
  owner,
  global,
  loading: loading.models.owner,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      data: [],
      selectedRowKeys: [],
      price_nature: [],
    };
  }


  componentDidMount() {
    const { dispatch } = this.props;
    const {
      owner: { pageLoaded, scrollData,searchParams },
    } = this.props;

    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        owner: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'owner/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'owner/changeLoaded',
          });
          dispatch({
            type: 'owner/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }

    });
    request(`/all_price_natures`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          price_nature: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    // document.addEventListener('keyup',this.keyupFunc)

  }
  keyupFunc=(e)=>{
    if(e.keyCode===13) {
      this.searchFunc()
    }
  }
  searchFunc=()=>{
    const that=this
    const { form , owner: { searchParams}} = that.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      that.handleSearch({
        page: 1,
        per_page: searchParams.per_page,
        ...fieldsValue,
        region_id:fieldsValue.region_id?fieldsValue.region_id.split('$')[0]:'',
        region_name:fieldsValue.region_id?fieldsValue.region_id.split('$')[1]:'',
        filter_level:'',
        filter_year:'',
      },function() {
        const {
          owner: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      });

    });
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'owner/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'owner/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    // document.removeEventListener('keyup',this.keyupFunc);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  findChildFunc = (cb) => {
    this.findChildLocation = cb;
  };
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    const {
      owner: {searchInputType,searchInputText },
    } = this.props;
    dispatch({
      type: 'owner/fetch',
      payload: {
        ...values,
        [searchInputType]:searchInputText
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const data = this.state.data;
    const { dispatch } = this.props;
    const {
      form: { getFieldDecorator },
      owner: { searchParams, selectedRowKeys,searchInputType,searchInputText },
    } = this.props;
    let branch_id=sessionStorage.getItem('branch_id');

    return (
      <Form layout="inline" className="search-form">
        <FormItem label="区域">
          {getFieldDecorator('region_id', {
            initialValue: searchParams.region_id?`${searchParams.region_id}$${searchParams.region_name}`:'',
          })(
            <TreeSelect
              style={{ width: '130px' }}
              allowClear
              treeDefaultExpandAll={Boolean(branch_id)}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              showSearch
            >
              {renderTreeNodes(data)}
            </TreeSelect>,
          )}
        </FormItem>
        <FormItem label="状态">
          {getFieldDecorator('status', {
            initialValue: searchParams.status,
          })(<Select style={{width:'90px'}}>
            <Option value={'0'}>全部</Option>
            <Option value={'1'}>正常</Option>
            <Option value={'-1'}>注销</Option>
          </Select>)}
        </FormItem>
        <FormItem label="余额状态">
          {getFieldDecorator('balance_status', {
            initialValue: searchParams.balance_status,
          })(<Select style={{width:'90px'}}>
            <Option value={'0'}>全部</Option>
            <Option value={'1'}>正常</Option>
            <Option value={'-1'}>欠费</Option>
          </Select>)}
        </FormItem>
        <FormItem label="口径">
          {getFieldDecorator('caliber', {
            initialValue: searchParams.caliber,
          })(   <Select style={{width:'100px'}}>
            {[{key:'全部',value:''},
              {key:'未知',value:'未知'},
              {key:'DN15',value:'DN15'},
              {key:'DN20',value:'DN20'},
              {key:'DN25',value:'DN25'},
              {key:'DN32',value:'DN32'},
              {key:'DN40',value:'DN40'},
              {key:'DN50',value:'DN50'},
              {key:'DN65',value:'DN65'},
              {key:'DN80',value:'DN80'},
              {key:'DN100',value:'DN100'},
              {key:'DN150',value:'DN150'},
              {key:'DN200',value:'DN200'},
              {key:'DN300',value:'DN300'},
            ].map(function(item,index) {
              return <Option key={index} value={item.value}>
                {item.key}
              </Option>
            })}
          </Select>)}
        </FormItem>
        <FormItem label="户主性质">
          {getFieldDecorator('account_nature', {
            initialValue: searchParams.account_nature,
          })(   <Select style={{width:'140px'}}>
            {[{key:'全部',value:''},
              {key:'个人',value:'个人'},{key:'个体工商户',value:'个体工商户'},
              {key:'企业',value:'企业'},{key:'政府机关',value:'政府机关'},{key:'教育系统',value:'教育系统'},
              {key:'医疗机构',value:'医疗机构'},{key:'事业单位',value:'事业单位'},
              {key:'军队',value:'军队'},{key:'社会团体',value:'社会团体'},
              {key:'国防机构',value:'国防机构'}, {key:'集体经济',value:'集体经济'},{key:'宗教团体',value:'宗教团体'},
              {key:'民办非企业单位',value:'民办非企业单位'},{key:'律师执业机构',value:'律师执业机构'},
              {key:'基金会',value:'基金会'},{key:'公正机构',value:'公正机构'},
              {key:'外国在华文化中心',value:'外国在华文化中心'},{key:'群众性团体组织',value:'群众性团体组织'},
              {key:'司法鉴定机构',value:'司法鉴定机构'},{key:'仲裁机构',value:'仲裁机构'},
              {key:'境外机构',value:'境外机构'},{key:'其他',value:'其他'}
            ].map(function(item,index) {
              return <Option key={index} value={item.value}>
                {item.key}
              </Option>
            })}
          </Select>)}
        </FormItem>
        <FormItem>
          <InputGroup compact>
            <Select onChange={(e)=>{
              dispatch({
                type: 'owner/changeOneProperty',
                payload: {
                  searchInputType:e
                },
              });
            }} style={{ width: '100px',color:'#000' }}  value={searchInputType}>
              <Option value="mobile">户主手机</Option>
              <Option value="name">户主姓名</Option>
              <Option value="meter_number">水表号</Option>
              <Option value="address">地址</Option>
            </Select>
            <Input style={{ width: '130px' }} value={searchInputText}  onKeyPress={this.keyPress} onChange={(e)=>{
              dispatch({
                type: 'owner/changeOneProperty',
                payload: {
                  searchInputText:e.target.value
                },
              });
            }} />
          </InputGroup>
        </FormItem>
   {/*     <FormItem label="户主姓名">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{ width: '130px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="户主手机">
          {getFieldDecorator('mobile', {
            initialValue: searchParams.mobile,
          })(<Input style={{ width: '130px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '130px' }} placeholder="请输入"/>)}
        </FormItem>*/}

        <FormItem>
          <Button
            id={'SEARCH_BTN'}
            type="primary"
            icon='search'
            onClick={() => {
              this.searchFunc()
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>

        </FormItem>
        {
          find(this.permissions, { name: 'meter_switch' }) &&
          <Fragment>
            <FormItem>
              <p style={{ marginBottom: 0 }}>已选 {selectedRowKeys.length} 个水表</p>
            </FormItem>
            <FormItem>

              <Button
                loading={this.state.openValveLoading}
                type={'primary'} style={{ marginLeft: 8 }} className={'btn-green'} icon='rocket'
                onClick={(e) => {
                  const that = this;
                  if (selectedRowKeys.length === 0) {
                    message.error('请先选择水表');
                    return false;
                  }
                  confirm({
                    title: `确定要对${selectedRowKeys.length}个水表开阀吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered: true,
                    maskClosable: true,
                    onOk() {
                      that.ChangeValve(1);
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }}>
                批量开阀
              </Button>
              <Button type={'danger'}
                      loading={this.state.closeValveLoading}
                      style={{ marginLeft: 8 }} icon='poweroff'
                      onClick={(e) => {
                        const that = this;
                        if (selectedRowKeys.length === 0) {
                          message.error('请先选择水表');
                          return false;
                        }
                        confirm({
                          title: `确定要对${selectedRowKeys.length}个水表关阀吗?`,
                          content: '请谨慎操作！',
                          okText: '确定',
                          okType: 'danger',
                          cancelText: '取消',
                          centered: true,
                          maskClosable: true,
                          onOk() {
                            that.ChangeValve(-1);
                          },
                          onCancel() {
                            console.log('Cancel');
                          },
                        });
                      }}>
                批量关阀
              </Button>
            </FormItem>
          </Fragment>
        }

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        owner: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.searchFunc()

      });
    }
  }
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'owner/add',
      payload: {
        ...formValues,
        region_id:formValues.region_id?formValues.region_id.split('$')[0]:'',
        benchmark_consumption:1000,
        area:1000,
      },
      callback() {
        message.success('添加户主成功');
        that.setState({
          addModal: false,
        });
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form,dispatch } = this.props;
    form.resetFields();
    const that = this;
    dispatch({
      type: 'owner/changeOneProperty',
      payload: {
        searchInputType:'mobile',
        searchInputText:'',
        searchParams:{
          region_id:"",
          region_name:'',
          account_nature:"",
          status:'0',
          balance_status:'0',
          caliber:'',
          name:'',
          mobile:'',
          meter_number:'',
          address:'',
          filter_level:'',
          filter_year:'',
          page: 1,
          per_page: 50,
        },
      },
      callback(){
        that.handleSearch({
          region_id: '',
          region_name: '',
          status:'0',
          caliber:'',
          balance_status:'0',
          filter_level:'',
          filter_year:'',
          address:'',
          page: 1,
          per_page: 50,
        });
      }
    });

  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `owner/edit`,
      payload: {
        ...formValues,
        region_id:formValues.region_id?formValues.region_id.split('$')[0]:'',
        id: this.state.editRecord.id,
        benchmark_consumption:1000,
        area:1000,
      },
      callback() {
        message.success('修改户主成功');
        that.setState({
          editModal: false,
        });
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleExport=()=>{
    const formValues = this.exportForm.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const payload= {
      meter_id:this.state.editRecord.meter_number,
      start_date:moment(formValues.start).format('YYYY-MM-DD'),
      end_date:moment(formValues.end).format('YYYY-MM-DD')
    }
    download(`${config.prefix}/meter_data_files?Authorization=Bearer ${sessionStorage.getItem('token')}&${formateObjToParamStr(payload)}`)

  }
  handleExportOwner=()=>{
    const {
      owner: { searchParams },
    } = this.props;
    console.log('searchParams',searchParams)
    download(`${config.prefix}/account_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr(searchParams)}`)

  }
  onRowsSelected = (rows) => {
    const {
      owner: { selectedRowKeys },
    } = this.props;
    this.props.dispatch({
      type: 'owner/changeSelectRow',
      payload: selectedRowKeys.concat(rows.map(r => r.rowIdx)),
    });
  };
  onRowsDeselected = (rows) => {
    let rowIndexes = rows.map(r => r.rowIdx);
    const {
      owner: { selectedRowKeys },
    } = this.props;
    this.props.dispatch({
      type: 'owner/changeSelectRow',
      payload: selectedRowKeys.filter(i => rowIndexes.indexOf(i) === -1),
    });
  };
  ChangeValve = (value) => {
    if (value === 1) {
      this.setState({
        openValveLoading: true,
      });
    } else {
      this.setState({
        closeValveLoading: true,
      });
    }
    const that = this;
    const {
      owner: { data, selectedRowKeys },
    } = this.props;
    console.log('selectedRowKeys', selectedRowKeys);
    let meter_ids = [];
    for (let i = 0; i < data.length; i++) {
      if (selectedRowKeys.indexOf(i) >= 0) {
        meter_ids.push(data[i].meter_number);
      }
    }
    console.log('meter_ids', meter_ids);
    request(`/meter_valve_switch`, {
      method: 'POST',
      data: {
        meter_ids: meter_ids,
        valve_status: value,
      },
    }).then((response) => {
      if (response.status === 200) {
        message.success(`${value === 1 ? '开阀' : '关阀'}指令下发成功`);

      }
      setTimeout(function() {
        that.setState({
          openValveLoading: false,
          closeValveLoading: false,
        });
      }, 5000);
    });
  };
  handleEditAccount = () => {
    const that = this;
    const formValues = this.EditAccountForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    request(`/accounts/${this.state.editRecord.id}`, {
      method: 'PUT',
      data: formValues,
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          editMeterModal: false,
        });
        message.success('修改成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  handleChangeInit= () => {
    const that = this;
    const formValues = this.changeInitForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    request(`/accounts/${this.state.editRecord.id}/initial_value`, {
      method: 'POST',
      data: {
        initial_value:formValues.initial_value
      },
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          changeInitModal: false,
          editRecord:{}
        });
        message.success('修改水表底数成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  handleReset=(id)=>{
    const that=this;
    request(`/accounts/${id}/reset`, {
      method: 'POST',
    }).then((response) => {
      if (response.status === 200) {
        message.success('重新扣费成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleSettle=(id)=>{
    const that=this;
    request(`/accounts/${id}/settle`, {
      method: 'POST',
    }).then((response) => {
      if (response.status === 200) {
        message.success('立即扣费成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleDisable=(id)=>{
    const that=this;
    request(`/accounts/${id}/disable`, {
      method: 'POST',
    }).then((response) => {
      if (response.status === 200) {
        message.success('注销账户成功');
        const {
          owner: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  render() {
    const that = this;
    const {
      owner: { data, loading, tableY, meta, searchParams, selectedRowKeys, summary },
      global: { gridTableW },
    } = this.props;
    const defaultColumnProperties = {
      resizable: true,
    };
    const username = sessionStorage.getItem('username')
    const renderMenuItem=function(row) {
      return <Menu onClick={({ key })=>{
        console.log('key',key)
        if(key === 'edit'){
          that.setState({
            editRecord: row,
            editModal: true,
          });
        }else if(key === 'change'){
          that.setState({
            editRecord: row,
            changeModal: true,
          });
        }else if(key === 'export'){
          that.setState({
            editRecord: row,
            exportModal: true,
          });
        }else if(key === 'changeInit'){
          that.setState({
            editRecord: row,
            changeInitModal: true,
          });
        }else if(key === 'reset'){
          confirm({
            title: `确定要对 "${row.meter_number}" 重新扣费吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleReset(row.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }else if(key === 'settle'){
          confirm({
            title: `确定要对 "${row.meter_number}" 立即扣费吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleSettle(row.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }else if(key === 'disable'){
          confirm({
            title: `确定要注销 "${row.meter_number}" 账户吗?`,
            content: '注销后不可恢复，请谨慎操作！',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleDisable(row.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }
      }
      }>
        <Menu.Item key={'export'}>
          导出水表读数
        </Menu.Item>
        {
          find(that.permissions, { name: 'account_add_and_edit' }) &&
          <Menu.Item key={'edit'}>
            编辑
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'meter_replace' }) &&
          <Menu.Item key={'change'}>
            换表
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'initial_value_edit' }) &&
          <Menu.Item key={'changeInit'}>
            修改水表底数
          </Menu.Item>
        }
      {/*   {
          find(that.permissions, { name: 'account_reset' })&&
          <Menu.Item key={'settle'}>
            账户立即扣费
          </Menu.Item>
        }
        {
          find(that.permissions, { name: 'account_settle' })&&
          <Menu.Item key={'reset'}>
            <span style={{color:'red'}}>账户重新扣费</span>
          </Menu.Item>
        } */}
        {
          find(that.permissions, { name: 'account_disable' })&&
          <Menu.Item key={'disable'}>
            <span style={{color:'red'}}>注销</span>
          </Menu.Item>
        }
      </Menu>
    }
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            owner: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '户主姓名',
        key: 'name',
        width: 180,
        frozen: true,
        formatter: (event) => {
          return <span title={event.row.name}>{event.row.name}</span>;
        },
      },
      {
        name: '户主手机',
        key: 'online_status',
        width: 100,
        formatter: (event) => {
          return <span title={event.row.mobile}>{event.row.mobile}</span>;
        },
      },
      {
        name: '户主地址',
        width: 200,
        key: 'address',
        formatter: (event) => {
          return <span title={event.row.address}>{event.row.address}</span>;
        },
      },
      {
        name: '户主性质',
        width: 80,
        key: 'account_nature',
      },
      {
        name: '用水性质',
        width: 128,
        key: 'price_nature',
        formatter:(event)=>{
          return <Popover title={event.row.price_nature.name} content={popoverPrice(event.row.price_nature)}>
            {event.row.price_nature.name}
          </Popover>
        }
      },
      {
        name: '水表号',
        width: 125,
        key: 'meter_number',
        formatter: (event) => {
          return <span title={event.value} style={{color:event.row.status===-1?'red':''}}>
            {event.row.status===-1&& <img style={{width:'22px',height:'22px',top:'-2px',position:'relative'}} src={stop} alt=""/>}
            {event.value}
          </span>;
        },
      },

      {
        name: '账户余额',
        width: 90,
        key: 'balance',
        formatter: (event) => {
          return <p
            className={Number(event.value) > Number(event.row.balance_alarm_amount) ? 'table-success table-status' :
              Number(event.value) >= 0 ? 'table-warm table-status' : 'table-error table-status'}>{event.value}</p>;
        },
      },
      {
        name: '上次抄表时间',
        width: 150,
        key: 'last_reading_time',
      },
      {
        name: '上次抄表读值(m3)',
        width: 130,
        key: 'last_reading_value',
      },
      {
        name: '阀门状态',
        key: 'valve_status',
        width: 80,
        formatter: (event) => {
          return renderValveOpen(event.value);
        },
      },
      {
        name: '信号强度',
        key: 'signal_intensity',
        width: 80,
        formatter: (event) => {
          return renderSignalIntensity(event.value);
        },
      },
      {
        name: '操作',
        width: 230,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
         {/*  {
            find(this.permissions, { name: 'counter_payment' }) && <Button
              className={'btn-gold'}
              type="primary"
              icon="pay-circle"
              size="small"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  payModal: true,
                });
              }
              }
            >充值
            </Button>
          } */}
          <Button
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
          {event.row.status === 1 &&
          <Dropdown overlay={renderMenuItem(event.row)} placement="bottomRight">
            <Button   size="small">更多<Icon type="down" /></Button>
          </Dropdown>
          }
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 60;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>业主信息</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item">
            <p>已管理水表数</p>
            <h4>{meta.total}</h4>
          </div>

          <div className="table-info-item" style={{color:'red'}}>
            <p style={{color:'red'}}>欠费金额</p>
            <h4 style={{color:'red'}}>{summary.total_arrear_amount}</h4>
          </div>
          <div size="large" className="table-info-right-item">
            {
              find(this.permissions, { name: 'account_export' }) &&
              <Tooltip title={'请先查询一次再导出'}>
                <Button
                  className={'btn-green'}
                  type="primary"
                  icon="export"
                  onClick={this.handleExportOwner}
                >导出远传表档案
                </Button>
              </Tooltip>
            }


            <Button
              icon="global"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    areaModal: true,
                  });
                }
              }
            >
              区域管理
            </Button>
            {
              find(this.permissions, { name: 'account_add_and_edit' }) &&
              <Button
                icon="plus"
                style={{ marginLeft: 8 }}
                type="primary"
                onClick={
                  () => {
                    this.setState({
                      addModal: true,
                    });
                  }
                }
              >
                添加户主
              </Button>
            }

          </div>

        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}

            rowSelection={{
              showCheckbox: true,
              enableShiftSelect: true,
              onRowsSelected: this.onRowsSelected,
              onRowsDeselected: this.onRowsDeselected,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}

          />
          {
            loading && <Loading/>
          }
        </div>
      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          owner: { scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop = 0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加远传表档案"/>}
        visible={this.state.addModal}
        centered
        onOk={this.handleAdd}
        width={1000}
        className="addModal"
        onCancel={() => {
          this.setState({ addModal: false });
        }}

      >
        <AddOrEditOwner price_nature={this.state.price_nature} data={this.state.data}
                        wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord && this.state.editRecord.name} `}/>}
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        destroyOnClose
        width={1000}
        className="editModal"
        onCancel={() => {
          this.setState({ editModal: false });
        }}

      >
        <AddOrEditOwner editRecord={this.state.editRecord} price_nature={this.state.price_nature} data={this.state.data}
                        wrappedComponentRef={(inst) => this.EditForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editMeterModal} modalClass="editMeterModal"
                                title={`修改"${this.state.editRecord.owner && this.state.editRecord.name}"下水表 ${this.state.editRecord.meter_number}`}/>}
        visible={this.state.editMeterModal}
        centered
        onOk={this.handleEditAccount}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        destroyOnClose
        className="editMeterModal"
        onCancel={() => {
          this.setState({ editMeterModal: false });
        }}

      >
        <AddOrEditAccount editRecord={this.state.editRecord} price_nature={this.state.price_nature}
                          wrappedComponentRef={(inst) => this.EditAccountForm = inst}/>

      </Modal>
      <Drawer
        title={`${this.state.editRecord && this.state.editRecord.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={780}
        visible={this.state.infoModal}
      >
        <Detail meter_number={this.state.editRecord.meter_number}
                id={this.state.editRecord.id}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.payModal} modalClass="payModal"
                                title={`${this.state.editRecord && this.state.editRecord.name} 充值`}/>}
        destroyOnClose
        visible={this.state.payModal}
        centered
        onOk={this.handleConfig}
        className="payModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={700}
        onCancel={() => {
          this.setState({ payModal: false, editRecord: {} });
        }}
        footer={[]}

      >
        <PayForm editRecord={this.state.editRecord} handleSearch={this.handleSearch}
                 wrappedComponentRef={(inst) => this.payForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.changeModal} modalClass="changeModal"
                                title={`${this.state.editRecord && this.state.editRecord.name} 换表`}/>}
        destroyOnClose
        visible={this.state.changeModal}
        centered
        onOk={this.handleConfig}
        className="changeModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={700}
        onCancel={() => {
          this.setState({ changeModal: false, editRecord: {} });
        }}
        footer={[]}

      >
        <ChangeMeter editRecord={this.state.editRecord} handleSearch={this.handleSearch}
                     wrappedComponentRef={(inst) => this.payForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.changeInitModal} modalClass="changeInitModal"
                                title={`${this.state.editRecord && this.state.editRecord.name} 修改水表底数`}/>}
        destroyOnClose
        visible={this.state.changeInitModal}
        centered
        onOk={this.handleChangeInit}
        className="changeInitModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={700}
        onCancel={() => {
          this.setState({ changeInitModal: false, editRecord: {} });
        }}

      >
        <ChangeInitValue editRecord={this.state.editRecord}
                     wrappedComponentRef={(inst) => this.changeInitForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.exportModal} modalClass="exportModal"
                                title={`导出 ${this.state.editRecord && this.state.editRecord.name} 水表数据`}/>}
        destroyOnClose
        visible={this.state.exportModal}
        centered
        onOk={this.handleExport}
        className="exportModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ exportModal: false, editRecord: {} });
        }}

      >
        <ExportMeterData editRecord={this.state.editRecord}
                     wrappedComponentRef={(inst) => this.exportForm = inst}/>
      </Modal>
      <Drawer
        title={`区域管理`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            areaModal: false,
            editRecord: {},
          });
        }}

        width={780}
        visible={this.state.areaModal}
      >
        <Area/>
      </Drawer>
    </div>;
  }
}

export default BasicList;
